package com.weather.common.utils.http;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * OkHttp HTTP工具类，自动携带X-QW-Api-Key请求头
 */
public class OkHttpUtils {
    private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);
    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 发送GET请求
     * @param url 请求URL
     * @param apiKey X-QW-Api-Key值（不再自动携带，仅保留参数以兼容）
     * @param queryParams 查询参数（可为null）
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String get(String url, String apiKey, Map<String, String> queryParams) throws IOException {
        return get(url, apiKey, queryParams, null);
    }

    /**
     * 发送GET请求，支持自定义请求头
     */
    public static String get(String url, String apiKey, Map<String, String> queryParams, Map<String, String> headers) throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (queryParams != null) {
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        Request.Builder requestBuilder = new Request.Builder()
                .url(urlBuilder.build());
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("GET请求失败: {} {}", response.code(), response.message());
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }

    /**
     * 发送POST请求（application/json）
     * @param url 请求URL
     * @param apiKey X-QW-Api-Key值（不再自动携带，仅保留参数以兼容）
     * @param jsonBody JSON字符串
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String postJson(String url, String apiKey, String jsonBody) throws IOException {
        return postJson(url, apiKey, jsonBody, null);
    }

    /**
     * 发送POST请求（application/json），支持自定义请求头
     */
    public static String postJson(String url, String apiKey, String jsonBody, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("POST请求失败: {} {}", response.code(), response.message());
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }

    /**
     * 发送POST请求（application/x-www-form-urlencoded）
     * @param url 请求URL
     * @param apiKey X-QW-Api-Key值（不再自动携带，仅保留参数以兼容）
     * @param formParams 表单参数
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String postForm(String url, String apiKey, Map<String, String> formParams) throws IOException {
        return postForm(url, apiKey, formParams, null);
    }

    /**
     * 发送POST请求（application/x-www-form-urlencoded），支持自定义请求头
     */
    public static String postForm(String url, String apiKey, Map<String, String> formParams, Map<String, String> headers) throws IOException {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (formParams != null) {
            for (Map.Entry<String, String> entry : formParams.entrySet()) {
                formBuilder.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody body = formBuilder.build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("POST请求失败: {} {}", response.code(), response.message());
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }
} 